// tableTrainRecords.js
// 本地模型的训练记录
class TrainRecordsTable {
    constructor(app, db) {
        this.app = app;
        this.db = db;
    }

    init() {
        const sqlTable = `
        CREATE TABLE IF NOT EXISTS train_records (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            local_model_id INTEGER NOT NULL,
            status TEXT NOT NULL,
            task_id TEXT DEFAULT '',
            output_dir TEXT DEFAULT '',
            model_path TEXT DEFAULT '',
            train_cfg TEXT DEFAULT '',
            create_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            update_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP
        );`;

        this.db.run(sqlTable, (err) => {
            if (err) {
                console.error('Create "train_records" Table Failed, Error: ', err);
            }
        });
    }

    // 插入train_records训练记录
    async insert(recordInfo) {
        // console.log('recordInfo = ', recordInfo);
        return new Promise((resolve, reject) => {
            const { local_model_id, status, task_id, output_dir, model_path, train_cfg } = recordInfo;
            const sqlInsert = `
                INSERT INTO train_records (local_model_id, status, task_id, output_dir, model_path, train_cfg, create_time, update_time )
                VALUES (?, ?, ?, ?, ?, ?, datetime(CURRENT_TIMESTAMP, '+8 hour') , datetime(CURRENT_TIMESTAMP, '+8 hour'));`;
            this.db.run(sqlInsert, [local_model_id, status, task_id, output_dir, model_path, train_cfg], function (err) {
                if (err) {
                    reject(err);
                } else {
                    resolve(this.lastID);
                }
            });
        });
    }

    // 更新数据集记录
    async update(recordInfo) {
        // console.log(`update recordInfo = `, recordInfo);
        return new Promise(async (resolve, reject) => {
            let sqlUpdateSQL = 'UPDATE train_records SET';
            const params = [];

            // update status if status property exitsted
            if (recordInfo.status !== null && recordInfo.status !== undefined) {
                sqlUpdateSQL += ' status = ?,';
                params.push(recordInfo.status);
            }

            // update task_id if task_id property exitsted
            if (recordInfo.task_id !== null && recordInfo.task_id !== undefined) {
                sqlUpdateSQL += ' task_id = ?,';
                params.push(recordInfo.task_id);
            }

            // update output_dir if output_dir property exitsted
            if (recordInfo.output_dir !== null && recordInfo.output_dir !== undefined) {
                sqlUpdateSQL += ' output_dir = ?,';
                params.push(recordInfo.output_dir);
            }

            // update model_path if model_path property exitsted
            if (recordInfo.model_path !== null && recordInfo.model_path !== undefined) {
                sqlUpdateSQL += ' model_path = ?,';
                params.push(recordInfo.model_path);
            }

            // update train_cfg if train_cfg property exitsted
            if (recordInfo.train_cfg !== null && recordInfo.train_cfg !== undefined) {
                sqlUpdateSQL += ' train_cfg = ?,';
                params.push(recordInfo.train_cfg);
            }

            // Remove the trailing comma and add the WHERE clause
            sqlUpdateSQL += " update_time = datetime(CURRENT_TIMESTAMP, '+8 hour') WHERE id = ?;";
            params.push(recordInfo.id);

            // Execute the UPDATE SQL statement
            this.db.run(sqlUpdateSQL, params, (err) => {
                if (err) {
                    console.error('Error updating train_records:', err.message);
                    reject({ code: -1, msg: err.message });
                }

                resolve({ code: 0, msg: 'Updated OK' });
            });
        });
    }

    async getRecord(record_id) {
        return new Promise((resolve, reject) => {
            const sqlQuery = `SELECT * FROM train_records WHERE id = ?;`;
            const params = [record_id];

            this.db.all(sqlQuery, params, (err, rows) => {
                if (err) {
                    reject(err);
                } else {
                    resolve(rows);
                }
            });
        });
    }

    // 返回某一个模型的训练记录
    async getRecords(local_model_id) {
        return new Promise((resolve, reject) => {
            const sqlQuery = `SELECT * FROM train_records${local_model_id ? ' WHERE local_model_id = ?' : ''};`;
            const params = local_model_id ? [local_model_id] : [];

            this.db.all(sqlQuery, params, (err, rows) => {
                if (err) {
                    reject(err);
                } else {
                    resolve(rows);
                }
            });
        });
    }

    // 删除某个记录
    async delete(record_id) {
        const deleteStatement = `
            DELETE FROM train_records WHERE id = ?;
        `;

        return new Promise((resolve, reject) => {
            this.db.run(deleteStatement, record_id, (err) => {
                if (err) {
                    reject(err.message);
                } else {
                    resolve(true);
                }
            });
        });
    }

    // 删除某个本地model_id的所有训练记录
    async deleteRecords(local_model_id) {
        const deleteStatement = `
            DELETE FROM train_records WHERE local_model_id = ?;
        `;

        return new Promise((resolve, reject) => {
            this.db.run(deleteStatement, local_model_id, (err) => {
                if (err) {
                    reject(err.message);
                } else {
                    resolve(true);
                }
            });
        });
    }
}
module.exports = { TrainRecordsTable };
